package sunyu.tools.redis;

import com.jfinal.kit.PropKit;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by 孙宇
 */
public class MyJedisCluster implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(MyJedisCluster.class);

    private ApplicationContext applicationContext;

    private String cluster = PropKit.use("config-redis.properties").get("redis.cluster");

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void init() {
        logger.info("动态注入JedisCluster到spring上下文");

        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();

        List<Map<String, String>> clusterList = (List<Map<String, String>>) Json.fromJson(cluster);
        if (clusterList != null && clusterList.size() > 0) {
            for (Map<String, String> c : clusterList) {
                jedisClusterNodes.add(new HostAndPort(c.get("host"), Integer.parseInt(c.get("port"))));
            }
        }

        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(JedisCluster.class);
        beanDefinitionBuilder.addConstructorArgValue(jedisClusterNodes);
        beanDefinitionBuilder.addConstructorArgReference("jedisPoolConfig");
        beanDefinitionBuilder.setDestroyMethodName("close");
        defaultListableBeanFactory.registerBeanDefinition("jedisCluster", beanDefinitionBuilder.getRawBeanDefinition());//注册到spring
    }

}
